package com.library.admin.config;

import com.library.admin.modules.book.service.BookService;
import com.library.admin.modules.borrowing.entity.Borrowing;
import com.library.admin.modules.borrowing.service.BorrowingService;
import com.library.common.enums.AuditStatusEnum;
import com.library.common.enums.BookBorrowingEnum;
import com.library.system.modules.examine.service.BorrowingAuditService;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 *
 * @author: xyh
 * @create: 2023-08-15
 **/
@Log4j2
@Configuration
public class BorrowingAuditConfig {

    @Resource
    private BorrowingService borrowingService;
    @Resource
    private BookService bookService;

    @Bean
    public BorrowingAuditService borrowingAuditService() {
        return new BorrowingAuditService() {
            @Override
            public void updateBorrowingStatus(Integer id, AuditStatusEnum statusEnum, String result) {
                Borrowing borrowing = borrowingService.getById(id);
                if (borrowing != null) {
                    //成功则扣费，失败不扣费
                    if (AuditStatusEnum.AUDIT_SUCCESS.getCode().equals(statusEnum.getCode())) {
                        if (borrowing.getFee().compareTo(BigDecimal.ZERO) != 0) {
                            borrowingService.updateUserBalance(borrowing.getFee(), borrowing.getUserId());
                        }
                        borrowing.setBorrowStatus(BookBorrowingEnum.RETURN.getCode());
                        bookService.updateBookNum(borrowing.getBookId(), borrowing.getQuantityNum(), false);
                    } else {
                        borrowing.setBorrowStatus(BookBorrowingEnum.RETURN_FAIL.getCode());
                    }
                    borrowing.setRemark(result);
                    borrowingService.updateById(borrowing);
                    log.info("还书流程结束：用户号：{}", borrowing.getJobNumber());
                }
            }
        };
    }
}
